import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowData;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;

public class TicketWnd {

	public static final String appName = "TicketRush 1.0";

	private Shell shell;
	private static Display display;
	private Menu menu;
	private Table table;

	private Label labelLoginRandCodeImage, labelLoginStatus,
			labelCookieImportStatus, labelOrderTicket, labelOrderRandCodeImage,
			labelOrderStatus;

	private Text textLoginName, textLoginPwd, textLoginRandCode,
			textFromStation, textToStation, textTravelDate, textUserName,
			textUserID, textUserMobile, textUser2Name, textUser2ID,
			textUser2Mobile, textUser3Name, textUser3ID, textUser3Mobile,
			textOrderRandCode, textCookieSessinID, textCookieBIGIPServer;

	private Button buttonQuery;

	private int loginTimes = 0;
	private int orderTimes = 0;

	private List<Train> trains = new ArrayList<Train>();

	private Train selectedTrain;

	private String selectedTicketType = null;

	private QueryTask queryThread;

	public TicketWnd() {
		display = new Display();
		shell = new Shell(display);
		initWindow();
	}

	private void initWindow() {
		shell.setText(appName);
		shell.setLayout(new RowLayout(SWT.VERTICAL));

		addMenuBar();
		addLoginModule();
		addSearchModule();
		addOrderModule();
		addStatusLine();

		doGetLoginRandCodeImageTask();
	}

	private void addMenuBar() {
		menu = new Menu(shell, SWT.BAR);
		shell.setMenuBar(menu);

		createMenuItem(menu, "关于", SWT.CTRL + 'C');
	}

	private void addLoginModule() {
		TabFolder tabFolder = new TabFolder(shell, SWT.NONE);
		tabFolder.setLayoutData(new RowData(860, 70));

		// 加一个Tab做本地登陆

		TabItem tabItem = new TabItem(tabFolder, SWT.NULL);
		tabItem.setText("本地登陆");

		Composite loginModule = new Composite(tabFolder, SWT.NONE);
		GridLayout layout = new GridLayout(8, false);
		loginModule.setLayout(layout);
		tabItem.setControl(loginModule);

		new Label(loginModule, SWT.RIGHT).setText("登陆用户:");

		textLoginName = new Text(loginModule, SWT.SINGLE | SWT.BORDER);
		textLoginName.setSize(100, 20);

		GridData data = new GridData(GridData.FILL_HORIZONTAL);
		data.widthHint = 60;
		textLoginName.setLayoutData(data);

		new Label(loginModule, SWT.RIGHT).setText("登陆密码:");

		textLoginPwd = new Text(loginModule, SWT.SINGLE | SWT.BORDER
				| SWT.PASSWORD);

		data = new GridData(GridData.FILL_HORIZONTAL);
		data.widthHint = 60;
		textLoginPwd.setLayoutData(data);

		new Label(loginModule, SWT.RIGHT).setText("登陆验证码:");

		labelLoginRandCodeImage = new Label(loginModule, SWT.LEFT);
		labelLoginRandCodeImage.setText("验证码读取中");

		data = new GridData();
		data.heightHint = 40;
		data.widthHint = 80;
		labelLoginRandCodeImage.setLayoutData(data);

		textLoginRandCode = new Text(loginModule, SWT.SINGLE | SWT.BORDER);
		textLoginRandCode.addKeyListener(new KeyAdapter() {

			@Override
			public void keyPressed(KeyEvent e) {
				if (e.character == SWT.CR) {
					doLogin();
				}
				super.keyPressed(e);
			}

		});

		Button button = new Button(loginModule, SWT.CENTER);
		button.setText("尝试登陆");
		button.addSelectionListener(new SelectionAdapter() {

			@Override
			public void widgetSelected(SelectionEvent e) {
				doLogin();
			}
		});

		new Label(loginModule, SWT.RIGHT).setText("登陆状态:");
		labelLoginStatus = new Label(loginModule, SWT.LEFT);
		labelLoginStatus.setText("未登录");

		data = new GridData(GridData.FILL_HORIZONTAL);
		data.horizontalSpan = 6;
		labelLoginStatus.setLayoutData(data);

		// 加一个Tab做cookie导入

		TabItem tabItem2 = new TabItem(tabFolder, SWT.NULL);
		tabItem2.setText("导入浏览器Cookie");

		Composite cookieModule = new Composite(tabFolder, SWT.NONE);
		GridLayout layout2 = new GridLayout(5, false);
		cookieModule.setLayout(layout2);
		tabItem2.setControl(cookieModule);

		new Label(cookieModule, SWT.RIGHT).setText("BIGipServerotsweb:");
		textCookieBIGIPServer = new Text(cookieModule, SWT.SINGLE | SWT.BORDER);
		data = new GridData(GridData.FILL_HORIZONTAL);
		textCookieBIGIPServer.setLayoutData(data);

		new Label(cookieModule, SWT.RIGHT).setText("JSESSIONID:");
		textCookieSessinID = new Text(cookieModule, SWT.SINGLE | SWT.BORDER);
		data = new GridData(GridData.FILL_HORIZONTAL);
		textCookieSessinID.setLayoutData(data);

		Button cookieButton = new Button(cookieModule, SWT.CENTER);
		cookieButton.setText("Cookie导入");
		cookieButton.addSelectionListener(new SelectionAdapter() {

			@Override
			public void widgetSelected(SelectionEvent e) {
				importCookie();
			}
		});

		new Label(cookieModule, SWT.RIGHT).setText("导入结果:");
		labelCookieImportStatus = new Label(cookieModule, SWT.RIGHT);
		labelCookieImportStatus.setText("未导入");
	}

	protected void importCookie() {
		if (null != textCookieBIGIPServer.getText()
				&& null != textCookieSessinID.getText()) {
			Map<String, String> cookieMap = new HashMap<String, String>();
			cookieMap.put("BIGipServerotsweb", textCookieBIGIPServer.getText());
			cookieMap.put("JSESSIONID", textCookieSessinID.getText());
			TicketRequestHelper.getInstance().setCookieMap(cookieMap);
			labelCookieImportStatus.setText("导入成功");
			doGetLoginRandCodeImageTask();
		}
	}

	private void addSearchModule() {
		Composite searchModule = new Composite(shell, SWT.NONE);
		searchModule.setLayoutData(new RowData(700, 40));
		GridLayout layout = new GridLayout(7, false);
		searchModule.setLayout(layout);

		new Label(searchModule, SWT.RIGHT).setText("始发站:");
		textFromStation = new Text(searchModule, SWT.BORDER);
		textFromStation.setText("北京西");

		GridData data = new GridData(GridData.FILL_HORIZONTAL);
		data.widthHint = 60;
		textFromStation.setLayoutData(data);

		new Label(searchModule, SWT.RIGHT).setText("终点站:");
		textToStation = new Text(searchModule, SWT.BORDER);
		textToStation.setText("广州东");

		data = new GridData(GridData.FILL_HORIZONTAL);
		data.widthHint = 60;
		textToStation.setLayoutData(data);

		new Label(searchModule, SWT.RIGHT).setText("乘车时间:");
		textTravelDate = new Text(searchModule, SWT.SINGLE | SWT.BORDER);
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.DAY_OF_MONTH, 11);
		textTravelDate.setText(new SimpleDateFormat("yyyy-MM-dd").format(cal
				.getTime()));

		buttonQuery = new Button(searchModule, SWT.TOGGLE);
		buttonQuery.setText("查询并保持刷新");
		buttonQuery.addSelectionListener(new SelectionAdapter() {

			@Override
			public void widgetSelected(SelectionEvent e) {
				boolean toogleStatus = ((Button) e.getSource()).getSelection();
				if (toogleStatus) {
					doQuery();
				} else {
					if (null != queryThread) {
						queryThread.terminalSignal = true;
					}
				}
			}

		});

		table = new Table(shell, SWT.MULTI | SWT.BORDER | SWT.FULL_SELECTION);
		table.setLinesVisible(true);
		table.setHeaderVisible(true);
		table.setLayoutData(new RowData(845, 230));

		TableColumn col1 = new TableColumn(table, SWT.LEFT);
		col1.setText("车次");
		col1.setWidth(50);
		TableColumn col2 = new TableColumn(table, SWT.LEFT);
		col2.setText("发车");
		col2.setWidth(120);
		TableColumn col3 = new TableColumn(table, SWT.LEFT);
		col3.setText("到站");
		col3.setWidth(120);
		TableColumn col4 = new TableColumn(table, SWT.LEFT);
		col4.setText("商务座");
		col4.setWidth(60);
		TableColumn col5 = new TableColumn(table, SWT.LEFT);
		col5.setText("特等座");
		col5.setWidth(60);
		TableColumn col6 = new TableColumn(table, SWT.LEFT);
		col6.setText("一等座");
		col6.setWidth(60);
		TableColumn col7 = new TableColumn(table, SWT.LEFT);
		col7.setText("二等座");
		col7.setWidth(60);
		TableColumn col8 = new TableColumn(table, SWT.LEFT);
		col8.setText("高级软卧");
		col8.setWidth(40);
		TableColumn col9 = new TableColumn(table, SWT.LEFT);
		col9.setText("软卧");
		col9.setWidth(40);
		TableColumn col10 = new TableColumn(table, SWT.LEFT);
		col10.setText("硬卧");
		col10.setWidth(40);
		TableColumn col11 = new TableColumn(table, SWT.LEFT);
		col11.setText("软座");
		col11.setWidth(40);
		TableColumn col12 = new TableColumn(table, SWT.LEFT);
		col12.setText("硬座");
		col12.setWidth(40);
		TableColumn col13 = new TableColumn(table, SWT.LEFT);
		col13.setText("无座");
		col13.setWidth(40);

		table.addMouseListener(new MouseAdapter() {

			@Override
			public void mouseDoubleClick(MouseEvent e) {
				// 得到选中的行
				Point point = new Point(e.x, e.y);
				final TableItem tableitem = table.getItem(point);
				if (null == tableitem) {
					return;
				}
				// 得到选中的列
				int column = -1;
				for (int i = 0; i < table.getColumnCount(); i++) {
					Rectangle rec = tableitem.getBounds(i);
					if (rec.contains(point))
						column = i;
				}
				final int col = column;
				if (col < 3 || col == -1) {
					return;
				}
				String trainStationCode = tableitem.getText(0);
				if (StringUtils.isBlank(trainStationCode)) {
					return;
				}
				if (null == trains || trains.isEmpty()) {
					return;
				}
				for (int i = 0; i < trains.size(); i++) {
					if (trainStationCode.equals(trains.get(i)
							.getStationTrainCode())) {
						selectedTrain = trains.get(i);
						String ticketInfo = selectedTrain.getStationTrainCode();
						switch (col) {
						case 3:
							ticketInfo += "商务座";
							selectedTicketType = "9";
							break;
						case 4:
							ticketInfo += "特等座";
							selectedTicketType = "P";
							break;
						case 5:
							ticketInfo += "一等座";
							selectedTicketType = "M";
							break;
						case 6:
							ticketInfo += "二等座";
							selectedTicketType = "O";
							break;
						case 7:
							ticketInfo += "高级软卧";
							selectedTicketType = "5";
							break;
						case 8:
							ticketInfo += "软卧";
							selectedTicketType = "4";
							break;
						case 9:
							ticketInfo += "硬卧";
							selectedTicketType = "3";
							break;
						case 10:
							ticketInfo += "软座";
							selectedTicketType = "2";
							break;
						case 11:
							ticketInfo += "硬座";
							selectedTicketType = "1";
							break;
						case 12:
							ticketInfo += "无座";
							selectedTicketType = "0";
							break;
						default:
							break;
						}
						labelOrderTicket.setText(ticketInfo);
						doGetOrderRandCodeImageTask();
						break;
					}
				}
			}

		});
	}

	private void addLine(Table table, String... params) {
		new TableItem(table, SWT.LEFT).setText(params);
	}

	private void addOrderModule() {
		Group orderModule = new Group(shell, SWT.NONE);
		orderModule.setLayoutData(new RowData(860, 180));
		orderModule.setText("订票信息");

		GridLayout layout = new GridLayout(6, false);
		orderModule.setLayout(layout);

		new Label(orderModule, SWT.LEFT).setText("车次信息:");
		labelOrderTicket = new Label(orderModule, SWT.NONE);
		GridData data = new GridData(GridData.FILL_HORIZONTAL);
		data.widthHint = 60;
		data.horizontalSpan = 5;
		labelOrderTicket.setLayoutData(data);
		labelOrderTicket.setText("请双击选择上表中有票的坐席，你也可以试试没票的:)");

		new Label(orderModule, SWT.RIGHT).setText("订票人1姓名:");
		textUserName = new Text(orderModule, SWT.BORDER);

		new Label(orderModule, SWT.RIGHT).setText("订票人1身份证:");
		textUserID = new Text(orderModule, SWT.BORDER);

		data = new GridData(GridData.FILL_HORIZONTAL);
		data.widthHint = 80;
		textUserID.setLayoutData(data);

		new Label(orderModule, SWT.RIGHT).setText("订票人1电话:");
		textUserMobile = new Text(orderModule, SWT.BORDER);
		data = new GridData(GridData.FILL_HORIZONTAL);
		data.widthHint = 60;
		textUserMobile.setLayoutData(data);

		new Label(orderModule, SWT.RIGHT).setText("订票人2姓名:");
		textUser2Name = new Text(orderModule, SWT.BORDER);

		new Label(orderModule, SWT.RIGHT).setText("订票人2身份证:");
		textUser2ID = new Text(orderModule, SWT.BORDER);

		data = new GridData(GridData.FILL_HORIZONTAL);
		data.widthHint = 80;
		textUser2ID.setLayoutData(data);

		new Label(orderModule, SWT.RIGHT).setText("订票人2电话:");
		textUser2Mobile = new Text(orderModule, SWT.BORDER);
		data = new GridData(GridData.FILL_HORIZONTAL);
		data.widthHint = 60;
		textUser2Mobile.setLayoutData(data);

		new Label(orderModule, SWT.RIGHT).setText("订票人3姓名:");
		textUser3Name = new Text(orderModule, SWT.BORDER);

		new Label(orderModule, SWT.RIGHT).setText("订票人3身份证:");
		textUser3ID = new Text(orderModule, SWT.BORDER);

		data = new GridData(GridData.FILL_HORIZONTAL);
		data.widthHint = 80;
		textUser3ID.setLayoutData(data);

		new Label(orderModule, SWT.RIGHT).setText("订票人3电话:");
		textUser3Mobile = new Text(orderModule, SWT.BORDER);
		data = new GridData(GridData.FILL_HORIZONTAL);
		data.widthHint = 60;
		textUser3Mobile.setLayoutData(data);

		new Label(orderModule, SWT.LEFT).setText("订票验证码:");
		labelOrderRandCodeImage = new Label(orderModule, SWT.NONE);
		data = new GridData();
		data.widthHint = 60;
		data.heightHint = 40;
		labelOrderRandCodeImage.setLayoutData(data);
		textOrderRandCode = new Text(orderModule, SWT.BORDER);
		textOrderRandCode.addKeyListener(new KeyAdapter() {

			@Override
			public void keyPressed(KeyEvent e) {
				if (e.character == SWT.CR) {
					doOrder();
				}
				super.keyPressed(e);
			}

		});

		Button button = new Button(orderModule, SWT.PUSH);
		button.setText("确认订票");
		data = new GridData();
		data.widthHint = 120;
		data.heightHint = 30;
		data.horizontalSpan = 3;
		button.setLayoutData(data);
		button.addSelectionListener(new SelectionAdapter() {

			@Override
			public void widgetSelected(SelectionEvent e) {
				doOrder();
			}

		});

		new Label(orderModule, SWT.NONE).setText("订票结果:");
		labelOrderStatus = new Label(orderModule, SWT.NONE);
		data = new GridData(GridData.FILL_HORIZONTAL);
		data.horizontalSpan = 5;
		labelOrderStatus.setLayoutData(data);
		labelOrderStatus.setText("暂无");
	}

	private void doQuery() {
		String fromStation = textFromStation.getText();
		String toStation = textToStation.getText();
		String date = textTravelDate.getText();
		if (null == queryThread) {
			queryThread = new QueryTask(display, fromStation, toStation, date);
			queryThread.start();
		} else {
			// 给原线程发送终止信号
			queryThread.terminalSignal = true;
			// 开启新线程
			queryThread = new QueryTask(display, fromStation, toStation, date);
			queryThread.start();
		}
	}

	private void doOrder() {
		if (null == selectedTrain || null == selectedTicketType) {
			labelOrderStatus.setText("还没有选择车次");
			return;
		}
		String userName = textUserName.getText();
		String userId = textUserID.getText();
		String userMobile = textUserMobile.getText();
		String orderRandCode = textOrderRandCode.getText();
		String date = textTravelDate.getText();
		if (!isNotBlank(orderRandCode, date)) {
			labelOrderStatus.setText("没有输入验证码");
			return;
		}
		List<User> users = new ArrayList<User>();
		if (isNotBlank(textUserName.getText(), textUserID.getText(),
				textUserMobile.getText())) {
			User user1 = new User();
			user1.setName(textUserName.getText());
			user1.setId(textUserID.getText());
			user1.setMobile(textUserMobile.getText());
			users.add(user1);
		}
		if (isNotBlank(textUser2Name.getText(), textUser2ID.getText(),
				textUser2Mobile.getText())) {
			User user2 = new User();
			user2.setName(textUser2Name.getText());
			user2.setId(textUser2ID.getText());
			user2.setMobile(textUser2Mobile.getText());
			users.add(user2);
		}
		if (isNotBlank(textUser3Name.getText(), textUser3ID.getText(),
				textUser3Mobile.getText())) {
			User user3 = new User();
			user3.setName(textUser3Name.getText());
			user3.setId(textUser3ID.getText());
			user3.setMobile(textUser3Mobile.getText());
			users.add(user3);
		}

		if (isNotBlank(userId, userName, userMobile, orderRandCode, date)) {
			OrderResult result = TicketRequestHelper.getInstance().order(
					selectedTrain, selectedTicketType, orderRandCode, users);
			if (result.successed) {
				labelOrderStatus.setText("订票成功，请在45分钟内登陆网站进行支付");
			} else {
				orderTimes++;
				labelOrderStatus.setText("[" + new Date() + "],第" + orderTimes
						+ "次订票失败，失败原因:" + result.error);
				doGetOrderRandCodeImageTask();
				textOrderRandCode.setText("");
			}
			
			
//			OrderTask task = new OrderTask();
//			task.display = display;
//			task.selectedTrain = selectedTrain;
//			task.selectedTicketType = selectedTicketType;
//			task.orderRandCode = orderRandCode;
//			task.users = users;
//			task.start();
		} else {
			// TODO
			labelOrderStatus.setText("请输入订票人信息");
		}
	}

	private void addStatusLine() {
		// TODO Auto-generated method stub

	}

	private MenuItem createMenuItem(Menu m, String t, int a) {
		MenuItem item = new MenuItem(m, 0);
		item.setText(t);
		if (a != 0)
			item.setAccelerator(a);
		return item;
	}

	public void run() {
		shell.setSize(900, 680);

		shell.open();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch())
				display.sleep();
		}
		display.dispose();
	}

	public static void main(String args[]) {
		TicketWnd main = new TicketWnd();
		main.run();
	}

	private void doGetLoginRandCodeImageTask() {
		new GetLoginRandCodeImageTask(display).start();
		// display.asyncExec(new GetLoginRandCodeImageTask());
	}

	private void doGetOrderRandCodeImageTask() {
		display.asyncExec(new GetOrderRandCodeImageTask());
	}

	private void doLogin() {
		String loginName = textLoginName.getText();
		String loginPwd = textLoginPwd.getText();
		String loginRandCode = textLoginRandCode.getText();
		loginTask task = new loginTask();
		task.display = display;
		task.loginName = loginName;
		task.loginPwd = loginPwd;
		task.loginRandCode = loginRandCode;
		task.start();
	}

	private boolean isNotBlank(String... params) {
		if (null == params)
			return false;
		for (int i = 0; i < params.length; i++) {
			String param = params[i];
			if (StringUtils.isBlank(param)) {
				return false;
			}
		}
		return true;
	}

	class loginTask extends Thread {

		Display display;
		String loginName;
		String loginPwd;
		String loginRandCode;
		boolean success = false;

		public void run() {
			while (!success && isNotBlank(loginRandCode, loginName, loginPwd)) {
				LoginResult result = TicketRequestHelper.getInstance().login(
						loginName, loginPwd, loginRandCode);
				if (result.successed) {
					loginSuccess();
					success = true;
				} else {
					// getLoginRandCode();
					loginTimes++;
					loginFail(result);
				}
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

		private void loginSuccess() {
			display.asyncExec(new Runnable() {

				@Override
				public void run() {
					labelLoginStatus.setText("登陆成功");
					textLoginName.setEditable(false);
					textLoginPwd.setEditable(false);
					textLoginRandCode.setEditable(false);

				}
			});
		}

		private void loginFail(final LoginResult result) {
			display.asyncExec(new Runnable() {

				@Override
				public void run() {
					textLoginRandCode.setText("");
					if (null == result.error) {
						labelLoginStatus.setText("[" + new Date() + "],第"
								+ loginTimes + "次登陆尝试失败，失败原因未知，请继续努力");
					} else {
						labelLoginStatus.setText("[" + new Date() + "],第"
								+ loginTimes + "次登陆尝试失败，失败原因:" + result.error
								+ "，请继续努力");
					}

				}
			});
		}

		private boolean getLoginRandCode() {
			byte[] tempBytes = null;
			int retry = 0;
			while (null == tempBytes && retry++ < 10) {
				try {
					tempBytes = TicketRequestHelper.getInstance()
							.getLoginRandCodeAsBytes();

				} catch (IOException e) {
					e.printStackTrace();
					try {
						Thread.sleep(3000);
					} catch (InterruptedException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				}
			}
			final byte[] imageBytes = tempBytes;
			display.asyncExec(new Runnable() {

				@Override
				public void run() {
					if (null != imageBytes) {
						Image ideaImage = new Image(null,
								new ByteArrayInputStream(imageBytes));
						labelLoginRandCodeImage.setImage(ideaImage);
					} else {
						labelLoginRandCodeImage.setText("无法读取验证码，网络忙或者无连接");
					}

				}
			});
			return true;
		}
	}

	class OrderTask extends Thread {
		Display display;
		List<User> users;
		Train selectedTrain;
		String selectedTicketType, orderRandCode;
		boolean success = false;

		public void run() {
			while (!success && null != selectedTrain
					&& isNotBlank(selectedTicketType, orderRandCode)
					&& null != users && users.size() > 0) {
				OrderResult result = TicketRequestHelper.getInstance()
						.order(selectedTrain, selectedTicketType,
								orderRandCode, users);
				if (result.successed) {
					orderSuccess();
				} else {
					orderTimes++;
					orderFail(result);
					// getOrderRandCode();
				}
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

		private void orderSuccess() {
			display.asyncExec(new Runnable() {
				public void run() {
					labelOrderStatus.setText("订票成功，请在45分钟内登陆网站进行支付");
				}
			});
		}

		private void orderFail(final OrderResult result) {
			display.asyncExec(new Runnable() {
				public void run() {
					labelOrderStatus.setText("[" + new Date() + "],第"
							+ orderTimes + "次订票失败，失败原因:" + result.error);
				}
			});
		}

		private boolean getOrderRandCode() {
			byte[] tempBytes = null;
			int retry = 0;
			while (null == tempBytes && retry++ < 10) {
				try {
					tempBytes = TicketRequestHelper.getInstance()
							.getOrderRandCodeAsBytes();

				} catch (IOException e) {
					e.printStackTrace();
					try {
						Thread.sleep(3000);
					} catch (InterruptedException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				}
			}
			final byte[] imageBytes = tempBytes;
			display.asyncExec(new Runnable() {

				@Override
				public void run() {
					if (null != imageBytes) {
						Image ideaImage = new Image(null,
								new ByteArrayInputStream(imageBytes));
						labelOrderRandCodeImage.setImage(ideaImage);
					} else {
						labelOrderRandCodeImage.setText("无法读取验证码，网络忙或者无连接");
					}

				}
			});
			return true;
		}
	}

	class GetLoginRandCodeImageTask extends Thread {

		public GetLoginRandCodeImageTask(Display display) {
			super();
			this.display = display;
		}

		Display display;

		public Display getDisplay() {
			return display;
		}

		public void setDisplay(Display display) {
			this.display = display;
		}

		public void run() {
			byte[] tempBytes = null;
			int retry = 0;
			while (null == tempBytes && retry++ < 10) {
				try {
					tempBytes = TicketRequestHelper.getInstance()
							.getLoginRandCodeAsBytes();

				} catch (IOException e) {
					e.printStackTrace();
					try {
						Thread.sleep(3000);
					} catch (InterruptedException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				}
			}
			final byte[] imageBytes = tempBytes;
			display.asyncExec(new Runnable() {

				@Override
				public void run() {
					if (null != imageBytes) {
						Image ideaImage = new Image(null,
								new ByteArrayInputStream(imageBytes));
						labelLoginRandCodeImage.setImage(ideaImage);
					} else {
						labelLoginRandCodeImage.setText("无法读取验证码，网络忙或者无连接");
					}

				}
			});
		}
	}

	class QueryTask extends Thread {

		boolean isRunning = false;

		boolean terminalSignal = false;

		Display display;

		String fromStation, toStation, date;

		public QueryTask(Display display, String fromStation, String toStation,
				String date) {
			super();
			this.display = display;
			this.fromStation = fromStation;
			this.toStation = toStation;
			this.date = date;
		}

		@Override
		public void run() {
			while (!terminalSignal) {
				isRunning = true;
				final QueryResult result = TicketRequestHelper.getInstance()
						.query(fromStation, toStation, date);
				if (!result.successed) {
					// TODO
					System.out.println(result.error);
				} else if (null == result.trains || result.trains.isEmpty()) {
					// TODO
				} else {
					display.asyncExec(new Runnable() {
						public void run() {
							table.clearAll();
							table.setItemCount(0);
							trains = result.trains;
							for (Train train : trains) {
								addLine(table, train.getStationTrainCode(), "["
										+ train.getTrainStartTime() + "] "
										+ train.getFromStationName(),
										"[" + train.getArriveTime() + "] "
												+ train.getToStationName(),
										train.getLeftSeat()[0],
										train.getLeftSeat()[1],
										train.getLeftSeat()[2],
										train.getLeftSeat()[3],
										train.getLeftSeat()[4],
										train.getLeftSeat()[5],
										train.getLeftSeat()[6],
										train.getLeftSeat()[7],
										train.getLeftSeat()[8],
										train.getLeftSeat()[9]);
							}
						}
					});

				}
				try {
					Thread.sleep(20000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			isRunning = false;
			System.out.println("查询线程终止");
		}

	}

	class GetOrderRandCodeImageTask extends Thread {

		@Override
		public void run() {
			labelOrderRandCodeImage.setImage(null);
			labelOrderRandCodeImage.setText("");
			byte[] imageBytes = null;
			try {
				imageBytes = TicketRequestHelper.getInstance()
						.getOrderRandCodeAsBytes();
			} catch (IOException e) {
				labelOrderRandCodeImage.setText("无法读取验证码，网络忙或者无连接");
			}
			if (null != imageBytes) {
				Image ideaImage = new Image(null, new ByteArrayInputStream(
						imageBytes));
				labelOrderRandCodeImage.setImage(ideaImage);
			} else {
				labelOrderRandCodeImage.setText("无法读取验证码，网络忙或者无连接");
			}
		}

	}
}
